package com.springcloudalibaba.gateway.filter.global;

import com.springcloudalibaba.bclass.enums.SysStateEnum;
import com.springcloudalibaba.bclass.util.LoggerUtil;
import com.springcloudalibaba.gateway.enums.GatewayFilterOrderEnum;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;

/**
 * @描述: TODO 出参全局过滤器，不需要在配置文件中配置，作用于所有的请求
 * @作者: lixing
 * @日期 2021/6/25 21:10
 */
@Component
public class MyResponseParamsGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public int getOrder() {
        return GatewayFilterOrderEnum.MY_RESPONSE_PARAMS.getValue();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 开始时间
        exchange.getAttributes().put("startTime", System.currentTimeMillis());
        //
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse originalResponse = exchange.getResponse();
        // 请求地址
        String reqPath = request.getPath().toString();
        // 请求方式：POST
        String method = request.getMethodValue();
        // 媒体类型：浏览器以JSON形式对资源进行解析
        MediaType mediaType = exchange.getRequest().getHeaders().getContentType();
        //
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {
                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);
                        byte[] bodyContent = new byte[join.readableByteCount()];
                        join.read(bodyContent);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        String bodyContentStr = new String(bodyContent, StandardCharsets.UTF_8);
                        //
//                        List<String> strings = exchange.getResponse().getHeaders().get(HttpHeaders.CONTENT_ENCODING);
//                        if (!CollectionUtils.isEmpty(strings) && strings.contains("gzip")) {
//                            GZIPInputStream gzipInputStream = null;
//                            try {
//                                gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(bodyContent), bodyContent.length);
//                                StringWriter writer = new StringWriter();
//                                IOUtils.copy(gzipInputStream, writer, "UTF-8");
//                                bodyContentStr = writer.toString();
//                            } catch (IOException e) {
//                                log.error("====Gzip IO error", e);
//                            } finally {
//                                if (gzipInputStream != null) {
//                                    try {
//                                        gzipInputStream.close();
//                                    } catch (IOException e) {
//                                        log.error("===Gzip IO close error", e);
//                                    }
//                                }
//                            }
//                        } else {
//                            bodyContentStr = new String(bodyContent, StandardCharsets.UTF_8);
//                        }
                        //
                        // 打印出参
                        LoggerUtil.info(MessageFormat.format("MyResponseParamsGlobalFilter 出参全局过滤器 ---- start [{0}]：{1}", method, reqPath));
                        String isDecrypt = null;
                        try {
                            isDecrypt = exchange.getAttributes().get("isDecrypt").toString();
                        } catch (Exception e) {
                            isDecrypt = SysStateEnum.STATE_NO.getDescribe();
                        }
                        if (SysStateEnum.STATE_YES.getDescribe().equalsIgnoreCase(isDecrypt)) {
                            LoggerUtil.info(MessageFormat.format("出参加密前: {0}", bodyContentStr));
                            LoggerUtil.info(MessageFormat.format("出参加密后: {0}", bodyContentStr));
                        } else {
                            LoggerUtil.info(MessageFormat.format("出参: {0}", bodyContentStr));
                        }

                        Long startTime = exchange.getAttribute("startTime");
                        if (null != startTime) {
                            LoggerUtil.info(MessageFormat.format("耗时: {0} 毫秒", String.valueOf(System.currentTimeMillis() - startTime)));
                        }
                        LoggerUtil.info("MyResponseParamsGlobalFilter 出参全局过滤器 ---- end");
                        LoggerUtil.info("");
                        //
                        return bufferFactory.wrap(bodyContent);
                    }));
                }
                // 直接返回
                return super.writeWith(body);
            }
        };
        //
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

}
